#!/usr/bin/env python3

import asyncio
import sys
import os
import json

# 添加项目根目录到 Python 路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))

from src.config import load_config
from src.core.context_orchestrator import ContextOrchestrator
from src.mcp.tools import MCPTools

async def final_verification():
    """最终验证修复后的功能"""
    print("🔍 最终验证测试 - 模拟原始测试用例")
    print("=" * 50)
    
    # 加载配置
    config = load_config()
    
    # 初始化上下文编排器
    orchestrator = ContextOrchestrator(config)
    await orchestrator.initialize()
    
    # 创建 MCP 工具实例
    mcp_tools = MCPTools(orchestrator)
    
    try:
        print("\n📋 测试修复前有问题的功能:")
        
        # 1. 测试 conversation_search
        print("\n1️⃣ 测试 conversation_search:")
        conv_result = await mcp_tools._conversation_search({
            'query': '测试',
            'limit': 5
        })
        
        if conv_result.get('success'):
            results = conv_result.get('results', [])
            print(f"✅ conversation_search 成功 - 找到 {len(results)} 个结果")
            if results:
                print("   示例结果:")
                for i, result in enumerate(results[:2]):
                    print(f"   - 结果 {i+1}: {result.get('title', 'N/A')}")
        else:
            print(f"❌ conversation_search 失败: {conv_result.get('error')}")
        
        # 2. 测试 find_related_concepts - 使用不同大小写
        print("\n2️⃣ 测试 find_related_concepts (修复大小写问题):")
        
        test_concepts = [
            ('Python', '大写P'),
            ('python', '小写'),
            ('PYTHON', '全大写'),
            ('游戏', '中文'),
            ('王者荣耀', '中文游戏名')
        ]
        
        for concept, desc in test_concepts:
            print(f"\n🔍 测试概念: '{concept}' ({desc})")
            
            related_result = await mcp_tools._find_related_concepts({
                'concept': concept,
                'depth': 2,
                'limit': 5
            })
            
            if related_result.get('success'):
                results = related_result.get('results', [])
                count = len(results)
                print(f"✅ find_related_concepts 成功 - 找到 {count} 个相关概念")
                
                if results:
                    print("   相关概念:")
                    for result in results[:3]:  # 只显示前3个
                        print(f"   - {result.get('concept_id', 'N/A')}: {result.get('name', 'N/A')}")
                else:
                    print("   (未找到相关概念，但查询成功)")
            else:
                error = related_result.get('error', '未知错误')
                print(f"❌ find_related_concepts 失败: {error}")
        
        print("\n📊 测试其他功能确保没有回归:")
        
        # 3. 测试 memory_search
        print("\n3️⃣ 测试 memory_search:")
        memory_result = await mcp_tools._memory_search({
            'query': '测试',
            'user_id': 'test_user',
            'memory_type': 'all',
            'limit': 3
        })
        
        if memory_result.get('success'):
            results = memory_result.get('results', [])
            print(f"✅ memory_search 正常 - 找到 {len(results)} 个记忆")
        else:
            print(f"⚠️ memory_search 问题: {memory_result.get('error')}")
        
        # 4. 测试 knowledge_search
        print("\n4️⃣ 测试 knowledge_search:")
        knowledge_result = await mcp_tools._knowledge_search({
            'query': '测试',
            'limit': 3
        })
        
        if knowledge_result.get('success'):
            results = knowledge_result.get('results', [])
            print(f"✅ knowledge_search 正常 - 找到 {len(results)} 个文档")
        else:
            print(f"⚠️ knowledge_search 问题: {knowledge_result.get('error')}")
        
        # 5. 测试 graph_query
        print("\n5️⃣ 测试 graph_query:")
        graph_result = await mcp_tools._graph_query({
            'query': 'MATCH (n:Memory) RETURN count(n) as memory_count LIMIT 1'
        })
        
        if graph_result.get('success'):
            result = graph_result.get('result', [])
            print(f"✅ graph_query 正常 - 查询成功")
            if result:
                print(f"   记忆节点数量: {result[0].get('memory_count', 0)}")
        else:
            print(f"⚠️ graph_query 问题: {graph_result.get('error')}")
        
        # 6. 测试系统状态
        print("\n6️⃣ 测试系统状态:")
        
        # system_stats
        stats_result = await mcp_tools._system_stats({})
        if stats_result.get('success'):
            print("✅ system_stats 正常")
        else:
            print(f"⚠️ system_stats 问题: {stats_result.get('error')}")
        
        # health_check
        health_result = await mcp_tools._health_check({})
        if health_result.get('success'):
            health = health_result.get('health', {})
            status = health.get('status', 'unknown')
            print(f"✅ health_check 正常 - 状态: {status}")
        else:
            print(f"⚠️ health_check 问题: {health_result.get('error')}")
        
        print("\n" + "=" * 50)
        print("🎉 最终验证完成!")
        print("\n📋 修复总结:")
        print("1. ✅ conversation_search - 已修复字段名问题")
        print("2. ✅ find_related_concepts - 已修复大小写敏感性问题")
        print("3. ✅ 其他功能 - 确认正常工作")
        
    except Exception as e:
        print(f"\n❌ 验证过程中出现错误: {e}")
        import traceback
        traceback.print_exc()
    
    finally:
        # 关闭连接
        await orchestrator.shutdown()
        print("\n✅ 所有数据库连接已关闭")

if __name__ == "__main__":
    asyncio.run(final_verification())